package org.cerberus.platform.share;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import org.cerberus.platform.internal.domain.IComponentClass;
import org.mortbay.util.ByteArrayOutputStream2;

public class BinaryPlatformOutputStream implements IPlatformOutputStream {

	private OutputStream stream;
	private ObjectOutputStream ostream;
	
	public BinaryPlatformOutputStream(OutputStream stream) throws IOException {
		this.stream = stream;
		this.ostream = new ObjectOutputStream(stream);
	}

	@Override
	public void flush() throws IOException {
		ostream.flush();
	}
	
	public void writeType(CommuncationType type) throws IOException {
		ostream.writeShort(type.ordinal());
	}
	
	@Override
	public void writeChange(Object[] data) throws IOException {
		writeType(CommuncationType.CHANGE);
	}

	@Override
	public void writeNewClass(IComponentClass clazz) throws IOException {
		
	}

	@Override
	public void writeNewObject(Object[] object) throws IOException {
		ostream.writeInt((Integer)object[0]);
		ostream.writeChars((String)object[1]);
		for (int i = 0; i < object.length; i++) {
			ostream.writeObject(object[i]);
		}
	}

	@Override
	public void writeRemoveClass(String classID) throws IOException {
		ostream.writeChars(classID);
	}

	@Override
	public void writeRemoveObject(Integer id) throws IOException {
		ostream.writeInt(id);
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
		ByteArrayOutputStream2 out = new ByteArrayOutputStream2();
		BinaryPlatformOutputStream pout = new BinaryPlatformOutputStream(out);
		
		long readTime = System.currentTimeMillis();
		for (int i = 0; i < 50000; i++) {
			pout.writeType(CommuncationType.CHANGE);
		}
		
		pout.writeType(CommuncationType.EOF);
		pout.flush();
		byte[] array = out.toByteArray();
		
		ByteArrayInputStream in = new ByteArrayInputStream(array);
		BinaryPlatformInputStream pin = new BinaryPlatformInputStream(in);
		
		CommuncationType type = null;
		while (!(type = pin.readType()).equals(CommuncationType.EOF)) {
			Object[] changes = pin.readChange();
//			System.out.println("Change: ");
//			System.out.println("id: "+changes[0]);
//			System.out.println("index: "+changes[1]);
//			System.out.println("object: "+changes[2]);
		}
		
		System.out.println(System.currentTimeMillis() - readTime+"ns");
		System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
		System.out.println(array.length);
		
	}

	@Override
	public void writePlatformID(Integer id) {
		
	}
	
	
}
